package dao.impl;

import vo.Order;
import java.sql.Timestamp;
import vo.Orderitem;
import dao.BaseDao;
import dao.IOrderDao;

import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.Query;

import java.util.Iterator;
import java.util.List;
public class OrderDao extends BaseDao implements IOrderDao {

	@Override
	public Order addOrder(Order o) {
		Session s=getSession();
		Transaction ts=s.beginTransaction();
		s.save(o);
		ts.commit();
		s.close();
		return o;
	}
	public Order getOrderById(int id){
		Session s=getSession();
		String hql="from Order where orderId=?";
		Query q=s.createQuery(hql);
		q.setParameter(0, id);
		List orders=q.list();
		s.close();
		return (Order)orders.get(0);
	}
	public void setOrder(Order o){
		Session ss=getSession();
		String hql="update Order set isPayment=:status where orderId=:orderId";
		Query query=ss.createQuery(hql);
		query.setParameter("status", o.getIsPayment());
		query.setParameter("orderId", o.getOrderId());
		query.executeUpdate();
		ss.close();
	}
	public List getOrderByNumber(String orderNumber){
		Session ss=getSession();
		String hql="from Order o fetch all properties where o.orderNumber=:orderNumber";
		Query query=ss.createQuery(hql);
		query.setParameter("orderNumber", orderNumber);
		List<Order> orders=(List<Order>)query.list();
		
		Iterator it=orders.get(0).getOrderitems().iterator();
		while(it.hasNext()){
			System.out.println(((Orderitem)it.next()).getGoodsId()+"id");
		}
		ss.close();
		return orders;
	}
	public List getAllOrder(){
		Session s=getSession();
		String hql="from Order";
		Query q=s.createQuery(hql);
		List orders=q.list();
		s.close();
		return orders;
	}
	public List getOrderByTime(Timestamp start,Timestamp end){
		Session s=getSession();
		String hql="from Order o where o.orderTime>:start and o.orderTime<:end ";
		Query q=s.createQuery(hql);
		q.setParameter("start",start);
		q.setParameter("end", end);
		List orders=q.list();
		s.close();
		return orders;
	}
	public List getOrderByUserName(String userName){
		Session s=getSession();
		String hql="from Order as o,Users as u where u.userName=:userName and o.users.userId=u.userId";
		Query q=s.createQuery(hql);
		q.setParameter("userName",userName);
		List orders=q.list();
		s.close();
		return orders;
	}
}
